﻿using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using 微信信息管理系统.Code.Model;

namespace 微信信息管理系统.Code.Service;

// [AppAuthorize]
public class NewClassService : IDynamicApiController
{
    private readonly IFreeSql _fsql;

    public NewClassService(IFreeSql fsql)
    {
        _fsql = fsql;
    }

    // 获取分页列表
    public async Task<Res<PageResult<NewClass>>> PostPage(PageInput input)
    {
        var query = _fsql.Select<NewClass>();
        if (!string.IsNullOrEmpty(input.Keywords))
        {
            query.Where(x =>
                x.ClassName.Contains(input.Keywords) ||
                x.Remark.Contains(input.Keywords)
            );
        }

        var result = await query.OrderByDescending(x => x.Id).Count(out long count).Page(input.Page, input.PerPage).ToListAsync();

        return new Res<PageResult<NewClass>>(new PageResult<NewClass>
            {
                count = (int) count,
                rows = result
            }
        );
    }


    public async Task<Res<object>> GetSelectList()
    {
        var List = await _fsql.Select<NewClass>().OrderByDescending(it => it.Id).ToListAsync(it => new {label = it.ClassName, value = it.Id});
        return new Res<object>(List);
    }

    public async Task<Res<NewClass>> Get(int id)
    {
        var NewClass = await _fsql.Select<NewClass>().Where(x => x.Id == id).ToOneAsync();
        return new Res<NewClass>(NewClass);
    }

    public async Task<Res<NewClass>> Post(NewClass NewClass)
    {
        try
        {
            var result = await _fsql.Insert<NewClass>(NewClass).ExecuteAffrowsAsync();
            return new Res<NewClass>(NewClass);
        }
        catch (Exception e)
        {
            return new Res<NewClass>("信息已经提交过了！", false);
        }
    }

    public async Task<Res<NewClass>> Put(NewClass input)
    {
        var fq = _fsql.Update<NewClass>();
        fq.Set(it => it.Remark == input.Remark);
        fq.Set(it => it.ClassName == input.ClassName);

        var result = await fq.Where(it => it.Id == input.Id).ExecuteAffrowsAsync();
        return new Res<NewClass>();
    }

    public async Task<Res<NewClass>> Delete(int id)
    {
        var any = await _fsql.Select<News>().AnyAsync(it => it.ClassId == id);
        if (any) throw Oops.Oh("该分类下有信息，不能删除！");
        
        var result = await _fsql.Delete<NewClass>(id).ExecuteAffrowsAsync();
        return new Res<NewClass>(null);
    }
}